package com.sa.litetwo.srv.card.service;

import net.ibizsys.paas.codelist.ICodeList;
import net.ibizsys.paas.control.grid.IGridColumn;
import net.ibizsys.paas.core.IDEField;
import net.ibizsys.paas.ctrlmodel.GridColumnModel;
import net.ibizsys.paas.ctrlmodel.ICtrlModel;
import net.ibizsys.paas.ctrlmodel.IGridModel;
import net.ibizsys.paas.data.DataObject;
import net.ibizsys.paas.demodel.DEModelGlobal;
import net.ibizsys.paas.demodel.IDataEntityModel;
import net.ibizsys.paas.entity.IEntity;
import net.ibizsys.paas.sysmodel.CodeListGlobal;
import net.ibizsys.paas.sysmodel.SysModelGlobal;
import net.ibizsys.paas.util.GlobalContext;
import net.ibizsys.paas.util.StringHelper;
import net.ibizsys.paas.util.spring.IBizOverride;
import net.ibizsys.paas.web.WebConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.sa.litetwo.srv.liteTwoSysModel;
import com.sa.litetwo.srv.card.entity.GG_CARD;
import com.sa.litetwo.srv.card.entity.GG_WORK;

/**
 * 
 * 
 * @author 开发201118
 */
@IBizOverride
@Component
public class USRGG_CARDService extends GG_CARDService
{

	public USRGG_CARDService()
	{
		super();
	}

	@Override
	protected void onBeforeCreate(GG_CARD et) throws Exception
	{
		// TODO Auto-generated method stub
		super.onBeforeCreate(et);
		if (et.getHY().equals("房地产/建筑"))
			et.setZN(et.getZn_fdc());
		else if (et.getHY().equals("互联网/IT"))
			et.setZN(et.getZn_hlw());
		else if (et.getHY().equals("商业零售"))
			et.setZN(et.getZn_syls());
		else if (et.getHY().equals("机械制造"))
			et.setZN(et.getZn_jxzz());
		else if (et.getHY().equals("生物医药"))
			et.setZN(et.getZn_swyy());
		else if (et.getHY().equals("金融银行"))
			et.setZN(et.getZn_jryh());
	}

	@Override
	protected void onBeforeUpdate(GG_CARD et) throws Exception
	{
		// TODO Auto-generated method stub
		super.onBeforeUpdate(et);
		if (et.getHY().equals("房地产/建筑"))
			et.setZN(et.getZn_fdc());
		else if (et.getHY().equals("互联网/IT"))
			et.setZN(et.getZn_hlw());
		else if (et.getHY().equals("商业零售"))
			et.setZN(et.getZn_syls());
		else if (et.getHY().equals("机械制造"))
			et.setZN(et.getZn_jxzz());
		else if (et.getHY().equals("生物医药"))
			et.setZN(et.getZn_swyy());
		else if (et.getHY().equals("金融银行"))
			et.setZN(et.getZn_jryh());
	}

	@Override
	protected void onAfterCreate(GG_CARD et) throws Exception
	{
		// TODO Auto-generated method stub
		super.onAfterCreate(et);
		this.index(et);
	}

	@Override
	protected void onAfterUpdate(GG_CARD et) throws Exception
	{
		// TODO Auto-generated method stub
		super.onAfterUpdate(et);
		this.index(et);
	}
	
	

	@Override
	protected void onAfterRemove(GG_CARD et) throws Exception
	{
		// TODO Auto-generated method stub
		super.onAfterRemove(et);
		
		IndexWriterConfig config = this.getIndexWriterConfig();
		IndexWriter indexWriter = null;
		try
		{
			indexWriter = getInexWriter(config);
			indexWriter.deleteDocuments(new Term("key", et.getGG_CARDId()));
		 
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (indexWriter != null)
					indexWriter.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
			
	}

	@Override
	protected void onAfterRemove(ArrayList<GG_CARD> list) throws Exception
	{
		// TODO Auto-generated method stub
		super.onAfterRemove(list);
		
		IndexWriterConfig config = this.getIndexWriterConfig();
		IndexWriter indexWriter = null;
		try
		{
			indexWriter = getInexWriter(config);
			for(GG_CARD et:list)
			{
				indexWriter.deleteDocuments(new Term("key", et.getGG_CARDId()));
			}
		 
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (indexWriter != null)
					indexWriter.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
			
	}

	protected IndexWriterConfig getIndexWriterConfig()
	{

		return new IndexWriterConfig(Version.LUCENE_41, this.getAnalyzer());
	}

	private IndexWriter getInexWriter(IndexWriterConfig config) throws IOException
	{

		String BasicDirectory = WebConfig.getCurrent().getAttribute("INDEXPATH", "C://index//");
		Directory directory = new SimpleFSDirectory(new File(BasicDirectory + "GG_CARD"));

		return new IndexWriter(directory, config);
	}

	public void index(GG_CARD et)
	{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		IndexWriterConfig config = this.getIndexWriterConfig();
		IndexWriter indexWriter = null;
		try
		{
			indexWriter = getInexWriter(config);

			JSONObject jo = getJSONString(getDEModel("GG_CARD"), et);

			String strName = "GG_WORK";
			JSONArray GG_WORK = new JSONArray();
			for (IEntity obj : et.getWORK())
			{
				GG_WORK.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_WORK);

			strName = "GG_EDU";
			JSONArray GG_EDU = new JSONArray();
			for (IEntity obj : et.getEDU())
			{
				GG_EDU.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_EDU);

			strName = "GG_GRDHONOR";
			JSONArray GG_GRDHONOR = new JSONArray();
			for (IEntity obj : et.getGRDHONOR())
			{
				GG_GRDHONOR.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_GRDHONOR);

			strName = "GG_CERTIF";
			JSONArray GG_CERTIF = new JSONArray();
			for (IEntity obj : et.getCERTIF())
			{
				GG_CERTIF.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_CERTIF);

			strName = "GG_GRDPOST";
			JSONArray GG_GRDPOST = new JSONArray();
			for (IEntity obj : et.getGRDPOST())
			{
				GG_GRDPOST.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_GRDPOST);

			strName = "GG_SKILL";
			JSONArray GG_SKILL = new JSONArray();
			for (IEntity obj : et.getSKILL())
			{
				GG_SKILL.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_SKILL);

			strName = "GG_ATTACH";
			JSONArray GG_ATTACH = new JSONArray();
			for (IEntity obj : et.getATTACH())
			{
				GG_ATTACH.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_ATTACH);

			strName = "GG_TRAIN";
			JSONArray GG_TRAIN = new JSONArray();
			for (IEntity obj : et.getTRAIN())
			{
				GG_TRAIN.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_TRAIN);

			strName = "GG_PROJ";
			JSONArray GG_PROJ = new JSONArray();
			for (IEntity obj : et.getPROJ())
			{
				GG_PROJ.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_PROJ);

			strName = "GG_OTHER";
			JSONArray GG_OTHER = new JSONArray();
			for (IEntity obj : et.getOTHER())
			{
				GG_OTHER.put(getJSONString(getDEModel(strName), obj));
			}
			jo.put(strName, GG_OTHER);

			String strDESC = this.getDESC(this.getGridModel(), et);
			Document doc = new Document();
			doc.add(new Field("key", et.getGG_CARDId(), Store.YES, Index.NOT_ANALYZED));
			doc.add(new Field("type", "GG_CARD", Store.YES, Index.NOT_ANALYZED));
			doc.add(new Field("title", et.getXM(), Store.YES, Index.ANALYZED));
			doc.add(new Field("desc", strDESC, Store.YES, Index.ANALYZED));
			doc.add(new Field("index", jo.toString(), Store.YES, Index.ANALYZED));
			if (et.getUpdateDate() == null)
			{
				doc.add(new Field("updatetime", "没有更新时间", Store.YES, Index.NOT_ANALYZED));
			}
			else
			{
				doc.add(new Field("updatetime", df.format(et.getUpdateDate()), Store.YES, Index.NOT_ANALYZED));
			}
			indexWriter.deleteDocuments(new Term("key", et.getGG_CARDId()));
			indexWriter.addDocument(doc);

		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (indexWriter != null)
					indexWriter.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}

	}

	private IGridModel grid = null;

	private IGridModel getGridModel()
	{

		if (grid == null)
		{
			try
			{
				grid = (IGridModel) getliteTwoSysModel().createObject("com.sa.litetwo.app.srv.card.ctrlmodel.GG_CARDMainGridModel");
				grid.init(null);
			}
			catch (Exception e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return grid;
	}

	public liteTwoSysModel getliteTwoSysModel()
	{
		liteTwoSysModel model = null;
		try
		{
			model = (liteTwoSysModel) SysModelGlobal.getSystem("com.sa.litetwo.srv.liteTwoSysModel");
		}
		catch (Exception ex)
		{
		}

		return model;
	}

	public IDataEntityModel getDEModel(String strDENAME)
	{

		IDataEntityModel demodel = null;
		try
		{
			demodel = DEModelGlobal.getDEModel("com.sa.litetwo.srv.card.demodel." + strDENAME + "DEModel");
		}
		catch (Exception ex)
		{
		}

		return demodel;
	}

	private JSONObject getJSONString(IDataEntityModel<IEntity> demodel, IEntity entity)
	{

		JSONObject jo = new JSONObject();
		try
		{
			Iterator<IDEField> fields = demodel.getDEFields();
			while (fields.hasNext())
			{
				IDEField defield = fields.next();
				if (defield.getDataType().indexOf("TEXT") >= 0 || defield.getDataType().indexOf("CODELIST") >= 0)
				{
					String strValue = DataObject.getStringValue(entity, defield.getName(), "");
					if (!StringHelper.isNullOrEmpty(strValue))
					{
						if (!StringHelper.isNullOrEmpty(defield.getCodeListId()))
						{
							try
							{
								ICodeList codelist = CodeListGlobal.getCodeList(defield.getCodeListId());
								if (codelist != null)
								{
									String strTMP = "";

									strTMP = codelist.getCodeListText(strValue, true);

									if (!StringHelper.isNullOrEmpty(strTMP))
										strValue = strTMP;
								}
							}
							catch (Exception ex)
							{
							}
						}

						jo.put(defield.getName(), strValue);
					}
				}
			}
		}
		catch (Exception ex)
		{
		}
		return jo;
	}

	private String getDESC(IGridModel gridmodel, IEntity entity)
	{

		String jo = "";
		try
		{
			Iterator<IGridColumn> fields = gridmodel.getGridColumns();
			while (fields.hasNext())
			{
				IGridColumn column = fields.next();
				if (!(column instanceof GridColumnModel))
					continue;

				GridColumnModel defield = (GridColumnModel) column;
				if ((!defield.getName().equalsIgnoreCase("xm")) && (!defield.getName().equalsIgnoreCase("updatedate")))
				{
					String strValue = DataObject.getStringValue(entity, defield.getName(), "");
					if (!StringHelper.isNullOrEmpty(strValue))
					{
						if (!StringHelper.isNullOrEmpty(defield.getCodeListId()))
						{
							try
							{
								ICodeList codelist = CodeListGlobal.getCodeList(defield.getCodeListId());
								if (codelist != null)
								{
									String strTMP = "";

									strTMP = codelist.getCodeListText(strValue, true);

									if (!StringHelper.isNullOrEmpty(strTMP))
										strValue = strTMP;
								}
							}
							catch (Exception ex)
							{
							}
						}

						jo = jo + "" + defield.getCaption() + "：" + strValue + "；";
					}
				}
			}
		}
		catch (Exception ex)
		{
		}
		return jo;
	}

	private synchronized Analyzer getAnalyzer()
	{

		if (GlobalContext.getCurrent().getValue("IKAnalyzer_maker") == null)
		{
			Analyzer analyzer = new IKAnalyzer();// maker的分词器，用的是非智能模式
			GlobalContext.getCurrent().setValue("IKAnalyzer_maker", analyzer);
			return analyzer;
		}
		else
		{
			return (Analyzer) GlobalContext.getCurrent().getValue("IKAnalyzer_maker");
		}
	}

}
